package controller

import (
	"github.com/gin-gonic/gin"
	"web/app"
	"web/app/dao"
	"web/app/enum"
	"web/app/mode"
	"xutil/xEncrypt"
)

type c_user struct {
	dao dao.User
}

func (c2 *c_user) login(c *gin.Context) {
	user := c.PostForm("user")
	pwd := c.PostForm("pwd")
	if len(user) == 0 || len(pwd) == 0 {
		app.Response(c, 400, "用户名或密码错误")
		return
	}

	err, u := c2.dao.Login(user, xEncrypt.Md5(pwd))
	if err != nil {
		app.Response(c, 400, "用户名或密码错误")
		return
	}

	err, token := app.SignToken(&app.AUTO{
		Uid:         u.Uid,
		Power:       enum.Auto_user,
		Time_upData: u.Uptime,
	})
	if err != nil {
		app.Response(c, 400, "令牌发放失败,请重新登录")
		return
	}
	app.Response_data(c, 200, "登录成功", token)
}

func (c2 *c_user) reg(c *gin.Context) {
	user := c.PostForm("user")
	pwd := c.PostForm("pwd")
	if len(user) == 0 || len(pwd) == 0 {
		app.Response(c, 400, "用户名或密码格式错误")
		return
	}

	err := c2.dao.Reg(user, xEncrypt.Md5(pwd))
	if err != nil {
		app.Response(c, 400, "用户名已存在")
		return
	}
	app.Response(c, 200, "注册成功,请前往登录")
}

func (c2 *c_user) newPwd(c *gin.Context) {
	oldPwd := c.PostForm("oldPwd")
	newPwd := c.PostForm("newPwd")
	uid, _ := c.Get("uid")
	if len(oldPwd) == 0 || len(newPwd) == 0 {
		app.Response(c, 400, "密码格式错误")
		return
	}
	err := c2.dao.NewPwd(uid.(int), xEncrypt.Md5(oldPwd), xEncrypt.Md5(newPwd))
	if err != nil {
		app.Response(c, 400, "原密码错误")
		return
	}
	app.Response(c, 200, "修改成功,请重新登录")
}

func (c2 *c_user) out(c *gin.Context) {
	uid, _ := c.Get("uid")
	err := c2.dao.Out(uid.(int))
	if err != nil {
		app.Response(c, 400, "退出失败")
		return
	}
	app.Response(c, 200, "退出成功")
}

func (c2 *c_user) get(c *gin.Context) {
	user := c.Query("user")
	if len(user) == 0 {
		app.Response(c, 400, "查询条件为空")
		return
	}
	err, u := c2.dao.Get(&mode.User{User: user})
	if err != nil {
		app.Response(c, 400, "用户不存在")
		return
	}
	app.Response_data(c, 200, "查询成功", u)
}

func (c2 *c_user) getAll(c *gin.Context) {
	var user mode.User
	err := c.ShouldBind(&user)
	if err != nil {
		app.Response(c, 400, "查询条件为空")
		return
	}
	err, list := c2.dao.GetAll(&user)
	if err != nil {
		app.Response(c, 400, "查询失败")
		return
	}
	app.Response_list(c, 200, "查询成功", list)
}

func (c2 *c_user) edit(c *gin.Context) {
	var user mode.User
	err := c.ShouldBind(&user)
	if err != nil {
		app.Response(c, 400, "参数错误")
		return
	}
	err = c2.dao.Edit(&user)
	if err != nil {
		app.Response(c, 400, "修改失败")
		return
	}
	app.Response(c, 200, "修改成功")
}

type i_user interface {
	login(c *gin.Context)
	reg(c *gin.Context)
	newPwd(c *gin.Context)
	out(c *gin.Context)
	get(c *gin.Context)
	getAll(c *gin.Context)
	edit(c *gin.Context)
}
